package rpc.remote.transport.netty.server;

import io.netty.channel.*;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.EventExecutorGroup;
import lombok.extern.slf4j.Slf4j;
import rpc.remote.dto.RpcRequest;
import rpc.remote.dto.RpcResponse;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName: NettyServerHandler
 * @Description:
 * @author: Kowk
 * @since:1.0.0
 */
@Slf4j
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    //使用原子性来保证线程安全
    private static final AtomicInteger atomicInteger = new AtomicInteger(1);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)  {
        try {
            RpcRequest request = (RpcRequest) msg;
            log.info("服务端接受到消息：{},times:{}",request,atomicInteger.getAndIncrement());
            RpcResponse messageFromServer = RpcResponse.builder().message("来自服务端的信息").build();
            ChannelFuture future = ctx.writeAndFlush(messageFromServer);
            future.addListener(ChannelFutureListener.CLOSE);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("服务端发生异常",cause);
        ctx.close();
    }
}
